package nl.maarten.docenthelp.entity;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;

public class Session 
{
	private String ID;
	
	private Socket socket;
	
	private DatagramSocket udpSocket;
	private InetAddress udpAddress;
	private DatagramPacket packet;
	
	private int udpPort = -1;
	
	private BufferedWriter out;
	
	private BufferedReader in;
	
	public Session(String ID, Socket socket, DatagramSocket udpSocket)
	{
		this.ID = ID;
		this.socket = socket;
		this.udpSocket = udpSocket;
		
		init();
	}
	
	private void init()
	{
		try 
		{
			out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
			in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		} 
		catch (IOException e) 
		{
			e.printStackTrace();
		}
	}
	
	public void sendMessage( String message )
	{
		if( udpPort != -1 && udpAddress != null)
		{
			packet = new DatagramPacket( message.getBytes(), message.getBytes().length, udpAddress, udpPort );
			try
			{
				udpSocket.send( packet );
			}
			catch( Exception e )
			{
				e.printStackTrace();
			}
		}
	}
	
	public String getIPAddress()
	{
		return socket.getInetAddress().toString();
	}

	public String getID() 
	{
		return ID;
	}
	
	public DatagramSocket getUdpSocket()
	{
		return udpSocket;
	}

	public Socket getSocket()
	{
		return socket;
	}

	public BufferedWriter getOut() 
	{
		return out;
	}

	public BufferedReader getIn() 
	{
		return in;
	}
	
	public void setUdpPort( int port )
	{
		this.udpPort = port;
	}
	
	public int getUdpPort()
	{
		return udpPort;
	}
	
	public void setUdpAddress( InetAddress udpAddress )
	{
		this.udpAddress = udpAddress;
	}
	
	public InetAddress getUdpAddress()
	{
		return udpAddress;
	}
}
